
const fs= require('fs');
const path=require('path');
const tools=require('../../tools.js');
let {HomePath,pkCreatedFile,getFileType}=tools;

let auConfig=global.au.config;

const manifest=require(HomePath('/core/public/manifest.json'));

function copyFile(srcPath, tarPath, cb) {
    let rs = fs.createReadStream(srcPath);
    rs.on('error', function(err) {
        if (err) {
            console.log('read error', srcPath)
        }
        cb && cb(err)
    });

    let ws = fs.createWriteStream(tarPath);
    ws.on('error', function(err) {
        if (err) {
            console.log('write error', tarPath)
        }
        cb && cb(err)
    });
    ws.on('close', function(ex) {
        cb && cb(ex)
    });

    rs.pipe(ws)
}
function copyFolder(srcDir, tarDir, cb) {
    fs.readdir(srcDir, function(err, files) {
        let count = 0;
        let checkEnd = function() {
            ++count == files.length && cb && cb()
        };

        if (err) {
            checkEnd();
            return
        }

        files.forEach(function(file) {
            let srcPath = path.join(srcDir, file);
            let tarPath = path.join(tarDir, file);

            fs.stat(srcPath, function(err, stats) {
                if (stats.isDirectory()) {
                    fs.mkdir(tarPath, function(err) {
                        if (err) {
                            return
                        }

                        copyFolder(srcPath, tarPath, checkEnd)
                    })
                } else {
                    copyFile(srcPath, tarPath, checkEnd)
                }
            })
        });

        //为空时直接回调
        files.length === 0 && cb && cb()
    })
}
function createdExtensionFile(compilation) {

    //生成manifest.json
    if(manifest.browser_action){
        manifest.browser_action.default_title=auConfig.info.name;
    }
    let fileStr=JSON.stringify({
        ...manifest,
        ...auConfig.info
    });
    pkCreatedFile.call(compilation,'extension/manifest.json',fileStr);
    //生成libs文件
    pkCreatedFile.call(compilation,'extension/popup.html',fs.readFileSync(HomePath('/core/public/popup.html'),'utf-8'));
    pkCreatedFile.call(compilation,'extension/icon.png',fs.readFileSync(HomePath('core/public/icon.png')),'utf-8');
}
function copyExtensionFiles(compilation){
    //删除temp文件夹
    if (!global.isDev) {
        tools.deleteFile(HomePath('/core/.au/.build'));
    }
    //copyFolder(HomePath('/public/libs'),HomePath('/dist/extension/lib'));
    //copyFile(HomePath('/core/public/icon.png'),HomePath((isDev?'/disDev':'/dist')+'/extension/icon.png'));
}

class Index{
    constructor(options){
    }
    apply(compiler){
        //执行完毕
        compiler.hooks.emit.tap('createdExtensionFile',createdExtensionFile);
        //执行结束
        compiler.hooks.afterEmit.tap('copyExtensionFiles',copyExtensionFiles);
    }
}
module.exports=Index;
